<html>

<head>
    <title>
        {{title}}
    </title>
</head>

<body>
    <h1>我是登录页面</h1>
    <form>
        <input type="text" id="username" name="username">
        <input type="password" id="password" name="password">
        <div id="error"></div>
        <img src="/getCaptcha" alt="验证码" id="captchaImg">
        <input type="text" name="captcha" id="captcha">
        <button class="btn" type="submit">登录</button>
    </form>
</body>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script>
$(function() {
    var username = $('#username');
    var password = $('#password');
    var captcha = $('#captcha');
    var captchaImg = $('#captchaImg');
    captchaImg.on('click', function(e) {
        e.target.src = '/getCaptcha?' + Math.floor(Math.random() * 100);
    })
    var error = $('#error');
    var btn = $('.btn');
    $('form').submit(function(event) {
        event.preventDefault();
        var user = $.trim(username.val());
        var userlen = user.length;
        if (userlen == 0) {
            error.text('用户名不能为空').show();
            return false;
        }
        var pass = $.trim(password.val());
        var passlen = pass.length;
        if (passlen == 0) {
            error.text('密码不能为空').show();
            return false;
        }
        var capt = $.trim(captcha.val());

        btn.attr('disabled', true);
        $.ajax({
            url: '/login',
            type: 'POST',
            dataType: 'json',
            data: {
                password: pass,
                username: user,
                captcha: capt
            },
            complete: function() {
                btn.attr('disabled', false);
            },
            success: function(data) {
                if (!data.success)
                    error.text(data.message).show();
                else
                    console.log(data)
                    location.href = '/'
            }
        });

    });
});
</script>

</html>